<template>
  <div class="exchange-management-page">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" ref="searchForm">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.searchKey"
            placeholder="名称、编号、关键字等"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
       
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
    >
      <el-table-column prop="id" label="序号" width="70"></el-table-column>
      <el-table-column prop="name" label="交易所名称" width="130">
        <template #default="scope">
          <span class="clickable-title" @click="handleTitleClick(scope.row)">
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="city" label="城市" width="120"></el-table-column>
      <el-table-column prop="businessScope" label="业务范围" width="500"></el-table-column>
      <el-table-column label="状态" width="80">
        <template #default="scope">
          <span :class="scope.row.status === 1 ? 'status-enabled' : 'status-disabled'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="500">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            type="text"
            :style="{ color: scope.row.status === 1 ? 'orange' : 'green' }"
            @click="scope.row.status === 1 ? handleDisable(scope.row) : handleEnable(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button
            type="text"
            :style="{ color: 'red' }"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑交易所"
      :visible.sync="editDialogVisible"
      width="50%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editFormRules"
        label-width="120px"
        class="edit-form"
      >
        <el-form-item label="交易所名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入交易所名称"></el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input v-model="editForm.city" placeholder="请输入所在城市"></el-input>
        </el-form-item>
        <el-form-item label="业务范围" prop="businessScope">
          <el-input
            v-model="editForm.businessScope"
            placeholder="请输入业务范围"
            type="textarea"
            rows="4"
          ></el-input>
        </el-form-item>
        <!-- 新增 introduction 字段 -->
        <el-form-item label="交易所简介" prop="introduction">
          <el-input
            v-model="editForm.introduction"
            placeholder="请输入交易所简介"
            type="textarea"
            rows="4"
          ></el-input>
        </el-form-item>
        <!-- 新增 business_area 字段 -->
        <el-form-item label="业务区域" prop="businessArea">
          <el-input v-model="editForm.businessArea" placeholder="请输入业务区域"></el-input>
        </el-form-item>
        <el-form-item label="官方网站" prop="website">
          <el-input v-model="editForm.website" placeholder="请输入官方网站"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ExchangeManagementUpdated",
  data() {
    return {
      // 搜索表单
      searchForm: {
        searchKey: "",
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      // 编辑弹窗相关
      editDialogVisible: false,
      editForm: {
        id: null,
        name: "",
        city: "",
        businessScope: "",
        introduction: "", // 新增字段
        businessArea: "", // 新增字段
        website: "",
        status: 1,
      },
      // 表单验证规则
      editFormRules: {
        name: [
          { required: true, message: "请输入交易所名称", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
        ],
        city: [
          { required: true, message: "请输入所在城市", trigger: "blur" },
        ],
        businessScope: [
          { required: true, message: "请输入业务范围", trigger: "blur" },
          { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
        ],
        introduction: [
          { required: false, message: "请输入交易所简介", trigger: "blur" },
          { min: 0, max: 1000, message: "长度在 0 到 1000 个字符", trigger: "blur" },
        ],
        businessArea: [
          { required: false, message: "请输入业务区域", trigger: "blur" },
          { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" },
        ],
        website: [
          { required: false, message: "请输入官方网站", trigger: "blur" },
          { type: "url", message: "请输入正确的网址格式", trigger: ["blur", "change"] },
        ],
      },
    };
  },
  created() {
    this.fetchTableData();
  },
  methods: {
    // 获取表格数据
    async fetchTableData() {
      this.tableLoading = true;
      try {
        const res = await this.$request.post(
          "/assets/carbonExchange/getListByTenantB",
          {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            ...this.searchForm,
          }
        );
        if (res.code === 200) {
          this.tableData = res.data.list;
          this.totalCount = res.data.total;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.tableLoading = false;
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },
    // 标题点击事件
    handleTitleClick(row) {
      if (row.website) {
        const url =
          row.website.startsWith("http") ? row.website : `https://${row.website}`;
        window.open(url, "_blank");
      } else {
        this.$message.warning("该交易所没有关联的网址");
      }
    },
    // 查看操作
    handleView(row) {
      const button = document.activeElement;
      const searchUrl = `https://baike.baidu.com/item/${encodeURIComponent(
        row.name
      )}`;
      window.open(searchUrl, "_blank");

      if (button && button.blur) {
        setTimeout(() => {
          button.blur();
          document.body.focus();
        }, 100);
      }
    },
    // 编辑操作 - 打开弹窗并回显数据
    handleEdit(row) {
      const button = document.activeElement;

      // 回显数据到编辑表单，包括新增的 introduction 和 business_area
      this.editForm = {
        id: row.id,
        name: row.name,
        city: row.city,
        businessScope: row.businessScope,
        introduction: row.introduction || "", // 回显数据，无则置空
        businessArea: row.businessArea || "", // 回显数据，无则置空
        website: row.website || "",
        status: row.status,
      };

      // 显示弹窗
      this.editDialogVisible = true;

      if (button && button.blur) {
        setTimeout(() => {
          button.blur();
          document.body.focus();
        }, 100);
      }
    },
    // 关闭弹窗
    handleDialogClose() {
      this.editDialogVisible = false;
      // 重置表单
      this.$refs.editForm && this.$refs.editForm.resetFields();
    },
    // 提交编辑表单
    async submitEditForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            // 调用后端更新接口，将新增字段一起提交
            const res = await this.$request.post(
              "/assets/carbonExchange/update",
              this.editForm
            );

            if (res.code === 200) {
              this.$message.success("更新成功");
              this.editDialogVisible = false;
              // 重新获取表格数据
              this.fetchTableData();
            } else {
              this.$message.error("更新失败：" + (res.msg || "未知错误"));
            }
          } catch (error) {
            console.error("更新失败:", error);
            this.$message.error("网络错误，请重试");
          }
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    // 添加交易所
    handleAddExchange() {
      this.$router.push("/exchange/add");
    },
    // 启用操作
    async handleEnable(row) {
      const button = document.activeElement;
      this.$confirm(`确定要启用交易所【${row.name}】吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await this.$request.post(
              "/assets/carbonExchange/updateStatus",
              { id: row.id, status: 1 } // 状态设为1表示启用
            );
            if (res.code === 200) {
              this.$message.success("启用成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("启用失败:", error);
            this.$message.error("启用失败，请重试");
          }
        })
        .finally(() => {
          if (button && button.blur) {
            setTimeout(() => {
              button.blur();
              document.body.focus();
            }, 100);
          }
        });
    },
    // 禁用操作
    async handleDisable(row) {
      const button = document.activeElement;
      this.$confirm(`确定要禁用交易所【${row.name}】吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await this.$request.post(
              "/assets/carbonExchange/updateStatus",
              { id: row.id, status: 2 } // 状态设为2表示禁用
            );
            if (res.code === 200) {
              this.$message.success("禁用成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("禁用失败:", error);
            this.$message.error("禁用失败，请重试");
          }
        })
        .finally(() => {
          if (button && button.blur) {
            setTimeout(() => {
              button.blur();
              document.body.focus();
            }, 100);
          }
        });
    },
    // 删除操作
    async handleDelete(row) {
      const button = document.activeElement;
      this.$confirm(
        `确定要删除交易所【${row.name}】吗？删除后不可恢复`,
        "提示",
        {
          type: "error",
        }
      )
        .then(async () => {
          try {
            const res = await this.$request.post(
              "/assets/carbonExchange/delete",
              { id: row.id }
            );
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败，请重试");
          }
        })
        .finally(() => {
          if (button && button.blur) {
            setTimeout(() => {
              button.blur();
              document.body.focus();
            }, 100);
          }
        });
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchTableData();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },
  },
};
</script>

<style scoped>
.exchange-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.clickable-title {
  cursor: pointer;
  transition: color 0.2s;
}

.clickable-title:hover {
  color: #66b1ff;
}

.status-enabled {
  color: green;
}

.status-disabled {
  color: #ff4d4f;
}

.edit-form {
  margin-top: 20px;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table td,
::v-deep .el-table th {
  text-align: center;
}

/* 响应式 */
@media screen and (max-width: 1200px) {
  .search-section {
    overflow-x: auto;
    padding-bottom: 15px;
  }
}
</style>